package com.vidaappv1;
/* this class is used to display all orders selected in BigMenu class
 * NOTE: if device is not in the same network as desired server, app will 
 * not go further than pDialog box. To avoid this, comment out line 110 and 125
 */
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class Order extends Activity {
	
    // Progress Dialog
    private ProgressDialog pDialog;
 
    //alertDialog
    private  AlertDialog alertDialog;
    private  AlertDialog creditsDialog;
    private  AlertDialog.Builder creditBuilder;
    private  AlertDialog cancelDialog;
    
    String  jOrder = "";
    String togo;
    ArrayList<OrderItems> currOrder = new ArrayList<OrderItems>();
    OrderAdapter aApt;
    double total=0;
   
    
    // url to create new product
    private static String url_set_order = "http://192.168.43.191/vida/set_order.php";
  
    JSONParser jsonParser = new JSONParser();
    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_BALANCE = "balance";
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_order);
		
		Button accountinfobutton = (Button)findViewById(R.id.button1);
		Button topupaccountbutton = (Button)findViewById(R.id.Button01);
		
		accountinfobutton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				startActivity(new Intent(getApplicationContext(),AccountInfo.class));
			}
		});
		
		topupaccountbutton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				startActivity(new Intent(getApplicationContext(),LoadCredits.class));				
			}
		});
		
		
		//for debugging purposes
		Log.e("Errors","info");
				
		//Get orders selected from menu
		Intent inIntent = getIntent();
		Bundle b = inIntent.getExtras();
		final String orderList =(String)b.get("Orders");
		
		//Create array of order items
		String[] listArray = orderList.split(",");

		int[] userOrders = new int[listArray.length];
		for(int i = 0; i<listArray.length;i++){
			userOrders[i]= Integer.parseInt(listArray[i]);
		}
		
		//Create an Array of Menu Items from enum Type
		OrderItems[] items = OrderItems.values();
		for(int i = 0;i<userOrders.length;i++){
			String currItem = items[userOrders[i]].getName();
			jOrder += currItem+ ",";
			currOrder.add(OrderItems.values()[userOrders[i]]);
			Log.d("Output Checker","Value: " +items[userOrders[i]].getName());
		}
		
		//output total
		for (int i =0;i <currOrder.size();i++){
			total += currOrder.get(i).getPrice();
		}
		TextView txtTotal = (TextView)findViewById(R.id.txtTotal);
		txtTotal.setText("Total:R"+total);
		
		//Get ListView to show orders
		ListView lv = (ListView)findViewById(R.id.listViewOrder);
		aApt = new OrderAdapter(currOrder,this);
		lv.setAdapter(aApt);
		registerForContextMenu(lv);
		
		
		//Dialog box request Take away or sit Down
		AlertDialog.Builder builder = new AlertDialog.Builder(Order.this);
		builder.setMessage("SitDown or Take Away");
		
		builder.setPositiveButton("Take Away", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				togo="yes";
				//COMMENT OUT THIS LINE TO NOT RUN PHP SCRIPTS
				new CreateOrder().execute();
			}
		});
		
		builder.setNegativeButton("Sit Down", new DialogInterface.OnClickListener() {
		
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				togo="no";
				
				//COMMENT OUT THIS LINE TO NOT RUN PHP SCRIPTS
				new CreateOrder().execute();
			}
		});
		
		//Create dialog
		alertDialog = builder.create();
////////////////////////////////////////////////////////////////////////////////////////////////////////
		//Dialog box request to confirm or not
		AlertDialog.Builder suretocancel = new AlertDialog.Builder(Order.this);
		suretocancel.setMessage("Are you sure you want to cancel your order?");
		
		suretocancel.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				startActivity(new Intent(getApplicationContext(),Home.class));
				
			}
		});
		
		suretocancel.setNegativeButton("No", new DialogInterface.OnClickListener() {
		
			@Override
			public void onClick(DialogInterface dialog, int which) {
				Intent returnintent = new Intent(getApplicationContext(),Order.class);
				returnintent.putExtra("Orders",orderList);
				startActivity(returnintent);
				
			}
		});

		cancelDialog = suretocancel.create();

		
		Button btnConfirm = (Button)findViewById(R.id.btnConfirm);
		btnConfirm.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				alertDialog.show();
			}
		});
		
		Button btncancel = (Button)findViewById(R.id.button7);
		btncancel.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				cancelDialog.show();
			}
		});
		
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		// TODO Auto-generated method stub

		AdapterContextMenuInfo aInfo = (AdapterContextMenuInfo) item.getMenuInfo();
		currOrder.remove(aInfo.position);
		
		
		//output total
		double total=0;
		for (int i =0;i <currOrder.size();i++){
			total += currOrder.get(i).getPrice();
		}
		TextView txtTotal = (TextView)findViewById(R.id.txtTotal);
		txtTotal.setText("Total:R"+total);
		
		aApt.notifyDataSetChanged();
		
		return super.onContextItemSelected(item);
		
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		// TODO Auto-generated method stub
		super.onCreateContextMenu(menu, v, menuInfo);
		
		AdapterContextMenuInfo aInfo = (AdapterContextMenuInfo) menuInfo;
		String listItem =  currOrder.get(aInfo.position).getName();
		
		menu.setHeaderTitle("Options for " + listItem);
		menu.add(1,1,1,"Delete");
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.order, menu);
		return true;
	}
	
	class CreateOrder extends AsyncTask<String,String,String>{
		 
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Order.this);
            pDialog.setMessage("Sending Order,please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
            
          //Dialog box for not enough vida credits
            creditBuilder = new AlertDialog.Builder(Order.this);
    		creditBuilder.setMessage("Sorry,Insufficient credits");
    		
    		creditBuilder.setPositiveButton("Top Up Credits", new DialogInterface.OnClickListener() {
    			
    			@Override
    			public void onClick(DialogInterface dialog, int which) {
	    				startActivity(new Intent(getApplicationContext(),LoadCredits.class));
	    				finish();
    			}
    		});
    		
    		creditBuilder.setNegativeButton("Home", new DialogInterface.OnClickListener() {
    		
    			@Override
    			public void onClick(DialogInterface dialog, int which) {
    				startActivity(new Intent(getApplicationContext(),Home.class));
    				finish();
    			}
    		});

        }
 
        /**
         * Creating product
         * */
        protected String doInBackground(String... args) {

            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("newOrder", jOrder));
            params.add(new BasicNameValuePair("pid", "5"));
            params.add(new BasicNameValuePair("quantity", "1"));
            params.add(new BasicNameValuePair("orderTime","11:11:11"));
            params.add(new BasicNameValuePair("extras","none"));
            params.add(new BasicNameValuePair("togo",togo));
            params.add(new BasicNameValuePair("total", String.valueOf(total)));
            params.add(new BasicNameValuePair("orderStatus","true"));
            // getting JSON Object
            // Note that create product url accepts POST method
            JSONObject json = jsonParser.makeHttpRequest(url_set_order,
                    "POST", params);
 
            // check log cat fro response
            Log.d("Create Response", json.toString());
 
            // check for success tag
            try {
                int success = json.getInt(TAG_SUCCESS);
                int balanceEnough = json.getInt(TAG_BALANCE);
                if (balanceEnough==0) {
                	// successfully created product
               	 runOnUiThread(new Runnable() {

                        @Override
                            public void run() {
                    		//Create dialog
                    		creditsDialog = creditBuilder.create();
                    		creditsDialog.show();
                        }
                       });
                }
                if (success == 1&&balanceEnough==1) {
                    // successfully created product
                	startActivity(new Intent(getApplicationContext(),OrderConfirmation.class));
                    
                	// closing this screen
                    finish();
                } else {
                    // failed to create product
                	//startActivity(new Intent(getApplicationContext(),Home.class));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }
 
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
            pDialog.dismiss();
        }
 	
		
		
		
		
		
		
	}
	
}
